package com.dnzx.socket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dnzx.exception.BizException;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketKeepAliveClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(SocketKeepAliveClient.class);

    private Socket socket = null;
    private OutputStream os = null;
    private InputStream is = null;


    private String ip;

    private int port;

    public SocketKeepAliveClient() {
    }

    public SocketKeepAliveClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    /**
     * 发送心跳包
     */
    private void sendHeartbeat() {
        try {
            String heartbeat = "heart:00001;";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(10 * 1000);// 10s发送一次心跳
                            os.write(heartbeat.getBytes());
                            os.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class SocketThread extends Thread {
        @Override
        public void run() {
            // long startTime = System.currentTimeMillis();
            try {
                if (socket == null || socket.isClosed()) {
//                    socket = new Socket(); // 连接socket
//                    SocketAddress endpoint = new InetSocketAddress(ip, port);
//                    socket.connect(endpoint);
//                    socket.setSoTimeout(5000);
                    socket = new Socket(ip, port); // 连接socket
                    os = socket.getOutputStream();
                }
                while (true) {
                    //  Thread.sleep(100);
                    System.out.println("=======");
                    BufferedReader br = null;
                    is = socket.getInputStream();
                    br = new BufferedReader(new InputStreamReader(is));
                    String info = null;
                    while ((info = br.readLine()) != null) {
                        System.out.println(info);
                        info += info;
                    }
//                    int size = is.available();
//                    if (size <= 0) {
//                        if ((System.currentTimeMillis() - startTime) > 3 * 10 * 1000) { // 如果超过30秒没有收到服务器发回来的信息，说明socket连接可能已经被远程服务器关闭
//                            socket.close(); // 这时候可以关闭socket连接
//                            startTime = System.currentTimeMillis();
//                        }
//                        continue;
//                    } else {
//                        startTime = System.currentTimeMillis();
//                    }
//                    byte[] resp = new byte[size];
//                    is.read(resp);
//                    String response = new String(resp, "utf-8");
                    // System.out.println(response);
                }
            } catch (Exception ex) {
                // e.printStackTrace();
                LOGGER.error("socket异常：" + ex.getMessage());
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e1) {
                    LOGGER.error("关闭资源异常：" + e1.getMessage());
                }
            } finally {
                try {
                    // 4.关闭资源
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e1) {
                    LOGGER.error("finally关闭资源异常：" + e1.getMessage());
                }
            }
        }
    }

    public String send(byte[] req) throws BizException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
//        String ip = SysParamConfServiceImpl.paramMap.get("PRINTER_IP");
//        String port = SysParamConfServiceImpl.paramMap.get("PRINTER_PROT");
        if (StringUtils.isBlank(ip)) {
            throw new BizException("打印机ip未配置");
        }
        if (port == 0) {
            throw new BizException("打印机端口未配置");
        }
        try {
//            if (os == null) {
//                new SocketKeepAliveClient(ip, Integer.valueOf(port)).new SocketThread().start();
//            }
            socket = new Socket(ip, port); // 连接socket
            os = socket.getOutputStream();
            if (os == null) {
                throw new BizException("请先连接打印机");
            }
            os.write(req);
            os.flush();
            // socket.shutdownOutput();// 关闭输出流
            // 3.获取输入流，并读取服务器端的响应信息
//            is = socket.getInputStream();
//            br = new BufferedReader(new InputStreamReader(is));
//            String info = null;
            //此方式会阻塞，不用此方式读取
//            while ((info = br.readLine()) != null) {
//                // System.out.println(info);
//                // info += info;
//                sb.append(info);
//            }
        } catch (UnknownHostException e) {
            LOGGER.error("发送打印异常：" + e.getMessage());
            throw new BizException("打印机连接错误");
        } catch (IOException e) {
            LOGGER.error("发送打印异常：" + e.getMessage());
            throw new BizException("打印错误");
        } finally {
            try {
                // 关闭资源
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e1) {
                LOGGER.error("finally关闭资源异常：" + e1.getMessage());
            }
        }
        return sb.toString();
    }

    public void shutDown() {
        try {
            // 关闭资源
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e1) {
            LOGGER.error("finally关闭资源异常：" + e1.getMessage());
        }
    }

}
